import java.io.*;
import java.net.*;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Hashtable;


public class CSE124Server {
    public static File server_dir;
    public static String file_location;
    public static Hashtable<String, data_content> cache = new Hashtable<String, data_content>();
    
    public static void main(String[] args) throws IOException {
        ThreadWorker threadWorker;
        int portNumber = 1234;
        String fileLocation = "data";
        Socket clientSocket = null;
        
        if (args.length < 1 || args.length > 2) {
        	System.out.println("Usage:  WebServer124 port_number [file_location]");
        	System.out.println("If [file_location] is not provided, the default location is \'data\'");
        	System.exit(-1);
        }
        
    	try{
    		portNumber = Integer.parseInt(args[0]);
    	}catch (NumberFormatException nfex){
    		System.out.println("Error: Invalid port number. Try again. Exiting...");
    		System.exit(-1);
    	}
    	
        /*if (args.length == 2) {
        	fileLocation = args[1];
        }	
        
        server_dir = new File(fileLocation);

        if(!server_dir.exists())
            server_dir.mkdir();
        else {
        	System.out.println("Current files in \'" +fileLocation+ "\' folder:");
        	for(int i = 0; i < server_dir.list().length; i++)
        		System.out.println(server_dir.list()[i]);
        }
       
        file_location = fileLocation;*/
        
        try {
            ServerSocket sock = new ServerSocket(portNumber);
            
            System.out.println("\n>>>> CSE124 WebSever is listening on port "+portNumber
            					+" and files location is at \'"+fileLocation+"\'\n");
            
            while(true) {
                try {
                	System.err.println(Thread.currentThread() + "(main thread) is waiting for input");
                    clientSocket = sock.accept();
                   // spawn a new thread for a new TCP connection
                    System.out.println("\n =============== Spawning a thread to handle a connection from: " +clientSocket.getInetAddress().getHostAddress()+" ===============");
                    threadWorker = new ThreadWorker(clientSocket, cache);
                    threadWorker.runThreadWorker();
                    
                } catch (IOException e1)
                {
                    System.out.println("ERROR: Connection from client failed");
                    System.exit(-1);
                }
                //System.out.println("Please enter server commands:");
            }
        }catch (IOException e) {
            System.out.println("Cannot listen to port: " + portNumber);
            System.exit(-1);
        }
       
        System.exit(0);
    }
}